﻿<?php 

		//require_once 'lib/facebook.php'; 
		
		function parse_signed_request($signed_request, $secret) {
		  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

		  // decode the data
		  $sig = base64_url_decode($encoded_sig);
		  $data = json_decode(base64_url_decode($payload), true);

		  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
			error_log('Unknown algorithm. Expected HMAC-SHA256');
			return null;
		  }

		  // check sig
		  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
		  if ($sig !== $expected_sig) {
			error_log('Bad Signed JSON signature!');
			return null;
		  }

		  return $data;
		}

		function base64_url_decode($input) {
		  return base64_decode(strtr($input, '-_', '+/'));
		}

		
	//if (empty($_SESSION["idUser"])){
		$app_id = "148131101921752";

		//$canvas_page = "http://supergaia.fdi.ucm.es:8060/moodvie/";
		 
		$canvas_page = "http://apps.facebook.com/moodvie";
		
		$secretito = "022b131f9f7beb85b71d2bd85e435e2b";

		/*$auth_url = "http://www.facebook.com/dialog/oauth?client_id=" 
				. $app_id . "&redirect_uri=" . urlencode($canvas_page);*/
		
		$auth_url = "http://www.facebook.com/dialog/oauth?client_id=" 
				. $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&canvas=1";

		$signed_request = $_REQUEST["signed_request"];


		$data = parse_signed_request($signed_request, $secretito);
		 
		/* foreach($data as &$item){
		  echo($item."/n");
		 }*/
			 
		 //echo(array_keys($data));
		 
		if (empty($data["user_id"]))
				echo("<script> top.location.href='" . $auth_url . "'</script>");
		else{
			include('loginbbdd.php');
			//include('vars.php');
			//compruebaUserBBDD($data["user_id"],$data["user_name"]);
			compruebaUserBBDD($data["user_id"],"sr normal");
			//compruebaUserBBDD(111,"manolo");
		}
	//}
		
     
	
     
 ?>